//
//  YearDatePickerView.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/16.
//

import UIKit

typealias BlockSelectYear = (_ startYear: String?, _ endYear: String?) ->Void

class YearDatePickerView: UIView {
    var titleStr: String = ""
    var dataArray: [Int] = []
    var selectYearBlock: BlockSelectYear!
    // MARK: - 公开属性
  
    /// 确定按钮背景色，默认蓝色
    var sureButtonBackgroundColor: UIColor? {
        didSet {
            sureButton.backgroundColor = sureButtonBackgroundColor
        }
    }

    /// 确定按钮字体颜色，默认白色
    var sureButtonTitleColor: UIColor? {
        didSet {
            sureButton.setTitleColor(sureButtonTitleColor, for: .normal)
        }
    }

    /// 年 背景水印，设置无色可以隐藏
    var yearPlaceholderColor: UIColor? {
        didSet {
            yearLabel.textColor = yearPlaceholderColor
        }
    }
    
    var contentHeight: CGFloat = 304 + IphoneXMarginBottom
    
    // MARK: - 私有属性
    ///底部view
     private var bottomView: UIView = {
       var tempView = UIView()
        tempView = UIView.init()
        tempView.backgroundColor = UIColor.white
        return tempView
     }()
    
    ///取消按钮
    private var cancelBtn: UIButton = {
        var btn = UIButton.init()
        btn.setTitle(MMLocalizedString("cancel", comment: "取消") , for: .normal)
        btn.setTitle(MMLocalizedString("cancel", comment: "取消"), for: .highlighted)
        btn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
        btn.setTitleColor(Theme.mainColor, for: .normal)
        btn.setTitleColor(Theme.mainColor, for: .highlighted)
        
        return btn
    }()
    
    ///确定按钮
    private var sureButton: UIButton = {
        var btn = UIButton.init()
        btn.setTitle(MMLocalizedString("confirm", comment: "确定"), for: .normal)
        btn.setTitle(MMLocalizedString("confirm", comment: "确定"), for: .highlighted)
        btn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
        btn.setTitleColor(Theme.mainColor, for: .normal)
        btn.setTitleColor(Theme.mainColor, for: .highlighted)
        return btn
    }()
    ///背景标题 2021
    private var yearLabel: UILabel = {
        let titleLab = UILabel.init()
        titleLab.backgroundColor = UIColor.clear
        titleLab.textColor = UIColor.init(hex: 0xeeeeee, alpha: 0.75)
        titleLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 110)
        titleLab.textAlignment = .center
        return titleLab
    }()
    
//    @IBOutlet private weak var bottomViewBottom: NSLayoutConstraint!
    ///选择器
    private var pickerView: UIPickerView = {
        let picker = UIPickerView.init()
        picker.backgroundColor = UIColor.clear
        return picker
    }()
    
    ///标题
    private var pickerTitleLab: UILabel = {
        let titleLab = UILabel.init()
        titleLab.backgroundColor = UIColor.clear
        titleLab.textColor = Theme.titleLabColor
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        titleLab.textAlignment = .center
        return titleLab
    }()
    
    private var lineView: UIView = {
        let tempView = UIView.init()
        tempView.backgroundColor = Theme.eColor
        return tempView

    }()

    private var startYear = "1950"
    private var endYear = "2023"
    
    func show() {
        if self.titleStr != "" {
            self.pickerTitleLab.text = self.titleStr
        }
        self.bottomView.snp.updateConstraints { (make) in
            make.height.equalTo(contentHeight)
        }
        setupData()
        UIApplication.shared.keyWindow!.addSubview(self)
        self.frame = UIScreen.main.bounds
        self.bottomView.snp.updateConstraints { (make) in
            make.bottom.equalTo(contentHeight)
        }
        self.layoutIfNeeded()
        bottomView.roundCorners(corners: UIRectCorner(arrayLiteral:  [.topLeft, .topRight]), radius: 10)
                                                                
        UIView.animate(withDuration: 0.24, animations: {
            self.bottomView.snp.updateConstraints { (make) in
                make.bottom.equalTo(0)
            }
            self.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0.5)
            
            self.layoutIfNeeded()
        }, completion: { (finish) in
  
        })
    }
    
    @objc func dismiss() {
        UIView.animate(withDuration: 0.24, animations: {
            self.bottomView.snp.updateConstraints { (make) in
                make.bottom.equalTo(self.contentHeight)
            }
            self.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0)
            
            self.layoutIfNeeded()
            
        }, completion: { (finished) in
            
            self.removeFromSuperview()
            
        })
    }

    @objc func onSureButtonAction() {
        self.selectYearBlock?(self.startYear,self.endYear)
        dismiss()
    }
    
    @objc func dismissAction() {
        self.dismiss()
    }
    
    ///布局
    func addSnpLayout() {
        self.bottomView.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(contentHeight)
            make.bottom.equalTo(contentHeight)
        }
        self.cancelBtn.titleLabel?.sizeToFit()
        let tempw1 = self.cancelBtn.titleLabel?.frame.size.width ?? 0
        self.cancelBtn.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.top.equalTo(0)
            make.size.equalTo(CGSize.init(width: tempw1 + 10, height: 56))
        }
        
        self.sureButton.titleLabel?.sizeToFit()
        let tempw2 = self.sureButton.titleLabel?.frame.size.width ?? 0
        self.sureButton.snp.makeConstraints { (make) in
            make.right.equalTo(0)
            make.top.equalTo(0)
            make.size.equalTo(CGSize.init(width: tempw2 + 10, height: 56))
        }
        
        self.pickerTitleLab.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(0)
            make.height.equalTo(56)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.top.equalTo(56)
            make.height.equalTo(0.5)
        }
        
        self.yearLabel.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(56)
        }
        
        self.pickerView.snp.makeConstraints { (make) in
            make.width.equalTo(kScreenWidth)
            make.height.equalTo(250)
            make.centerX.equalTo(self.bottomView.snp.centerX)
            make.top.equalTo(56)
//            make.centerY.equalTo(self.bottomView.snp.centerY)
        }
    }
    
    //获取年份的值
    private func setupData() {
        let currentYear = Calendar.current.component(.year, from: Date())
        self.dataArray = (1950...currentYear).map { $0 }
    }
    
    //记录选中的值
      func scrollTo(_ start: String?, end: String) {
        var startYearIndex = 0
        var endYearIndex = 0
        for yearIndex in 0 ..< self.dataArray.count{
            let yearStr = "\(self.dataArray[yearIndex])"
            if yearStr == start{
                startYearIndex = yearIndex
            }
            if yearStr == end{
                endYearIndex = yearIndex
            }
        }
        
        pickerView.selectRow(startYearIndex, inComponent: 0, animated: true)
        pickerView.selectRow(endYearIndex, inComponent: 1, animated: true)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
            self.setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     func setupUI() {
        
        self.setupData()
        
        self.pickerTitleLab.text = MMLocalizedString("year_manufacture", comment: "制造年份")
        self.pickerTitleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        self.pickerTitleLab.textColor = UIColor.init(hex: 0x111A34)
        backgroundColor = UIColor.init(hex: 0x000000, alpha: 0)
        
        self.addSubview(bottomView)
        bottomView.addSubview(cancelBtn)
        bottomView.addSubview(sureButton)
        bottomView.addSubview(pickerTitleLab)
        bottomView.addSubview(lineView)
        bottomView.addSubview(yearLabel)
        bottomView.addSubview(pickerView)
        
        self.addSnpLayout()

        let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss))
        tap.delegate = self
        addGestureRecognizer(tap)

        pickerView.delegate = self
        pickerView.dataSource = self
        cancelBtn.addTarget(self, action: #selector(dismissAction), for: .touchUpInside)
        sureButton.addTarget(self, action: #selector(onSureButtonAction), for: .touchUpInside)
        
       
    }
    
   
    
 
}




    
    




// MARK: - UIGestureRecognizerDelegate
extension YearDatePickerView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        guard let touchView = touch.view else { return false }

        if touchView.isDescendant(of: bottomView) {
            // 点击的view是否是bottomView或者bottomView的子视图
            return false
        }

        return true
    }
}

// MARK: - UIPickerViewDelegate, UIPickerViewDataSource
extension YearDatePickerView: UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 2
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.dataArray.count
    }

    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 40
    }

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

        var title: String = " "
        title =  "\(self.dataArray[row])"
         
        if let label = view as? UILabel {
            label.text = title
            return label
        }

        let label = UILabel()
        label.textAlignment = .center
        label.font = UIFont.init(name: Theme.PingFangSCMedium, size: 18)
        label.text = title
        label.sizeToFit()
        return label
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0{
            self.startYear = "\(self.dataArray[row])"
        }else{
            self.endYear = "\(self.dataArray[row])"
        }
    }
    
}
